// 单项链表
// 节点
import router from "@/router";

class Node {
    constructor(el) {
        this.el = el;
        this.next = null;
    }
}

const linkedList = class LinkedList {
    constructor(){
        this.head = new Node('head')
        this.siz = 0
    }

    size() {
        return this.siz
    }

    // 用于查找
    findVal(item){
        let currentNode = this.head
        while (currentNode !== null && currentNode.el !== item) {
            currentNode = currentNode.next;
        }
        return currentNode
    }

    findIdx(index) {
        let cur = this.head
        let temp = 0
        while (cur.next !== null && temp !== index) {
            cur = cur.next
            temp ++;
        }
        return cur.next;
    }


    findPreVal(item) {
        let cur = this.head
        while (cur.next !== null && cur.next.el !== item) {
            cur = cur.next
        }
        return cur
    }

    // 插入节点
    // el:要插入的数据
    // item：数据插入到这个节点后面
    insertVal(el, item){
        const newNode = new Node(el)
        const cur = this.findVal(item)
        newNode.next = cur.next
        cur.next = newNode
        this.siz ++
    }
    insertIdx(el, index) {
        let cur
        if (index > 0)
            cur = this.findIdx(index - 1)
        else
            cur = this.head;

        const newNode = new Node(el)
        newNode.next = cur.next
        cur.next = newNode
        this.siz ++
    }

    // 删除指定节点的下一个结点
    removeVal(item){
        const preNode = this.findPreVal(item)
        if (preNode.next !== null) {
            preNode.next = preNode.next.next
        }
        this.siz --
    }
    removeIdx(index) {
        let cur
        if (index > 0) {
            cur = this.findIdx(index - 1)
        } else {
            cur = this.head;
        }
        if (cur.next !== null)
            cur.next = cur.next.next
        this.siz --
    }
}

export default {Node,LinkedList}